﻿using System;
using System.Windows.Forms;
using NetworkSerialPort.Helper;
using oModbus.Message;

namespace NetworkSerialPort
{
    public partial class ServiceForm : Form
    {
        public ServiceForm()
        {
            InitializeComponent();
        }
        private void Service_Load(object sender, EventArgs e)
        {
            txtPort.Text = ConfigureAppConfig.GetConnectionStringsValue("Port");
            ip_txt.Text = ConfigureAppConfig.GetConnectionStringsValue("Ip");
            btnStart_Click(null, null);
        }
        private void _communServer_LogEvent(string title, string data)
        {
            if (ckbShow.Checked)
            {

                if (txtInfo.InvokeRequired)
                {
                    //后端线程向主线程记日志
                    Invoke(new Action<string, string>(_communServer_LogEvent), title, data);
                }
                else
                {
                    //主线程直接记日志

                    if (ckbHex.Checked)
                    {
                        //txtInfo.Text += title + data.GetHexString()+ Environment.NewLine;
                        txtInfo.Text += title + data + Environment.NewLine;
                    }
                    else
                    {
                        // txtInfo.Text += title + data.GetHexString() + Environment.NewLine;
                        txtInfo.Text += title + data + Environment.NewLine;
                    }
                }

            }

        }

        private NetworkSerialService _communServer;
        private void btnStart_Click(object sender, EventArgs e)
        {

            int port;
            if (!int.TryParse(txtPort.Text, out port))
            {
                MessageBox.Show(@"输入值不是合法的数字", @"错误");
                return;
            }
            var log = new LogInfo("log4net.config", "");
            //通信服务
            _communServer = new NetworkSerialService(port, log);
            _communServer.LogEvent += _communServer_LogEvent;
            _communServer.Start();
            btnStart.Enabled = false;
            btnStop.Enabled = true;

        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (_communServer != null)
            {
                _communServer.Stop();
                _communServer = null;
            }

            btnStop.Enabled = false;
            btnStart.Enabled = true;

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtInfo.Text = "";
        }
        private void btnSend_Click(object sender, EventArgs e)
        {
            ushort startAddress = 100;
            ushort number = 5;

            ReadCoilRequest request = new ReadCoilRequest(1, startAddress, number);
            byte[] data = request.PackingMessage();
            _communServer.SendAll(data);
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}
